# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup

if __name__ == '__main__':
    headers = {
        'User_Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
    }
    url = 'https://www.shicimingju.com/book/sanguoyanyi.html'
    response = requests.get(url,headers)
    response.encoding = 'utf-8'
    soup = BeautifulSoup(response.text,'lxml')
    li_list = soup.select('.book-mulu > ul a')
    f = open('sanguo.txt','w',encoding='utf-8')
    for li in li_list:
        li_text = li.string
        detail_url = 'https://www.shicimingju.com/' + li['href']
        detail_text = requests.get(url=detail_url,headers=headers)
        detail_text.encoding = detail_text.apparent_encoding
        detail_soup = BeautifulSoup(detail_text.text,'lxml')
        div_tag = detail_soup.find('div',class_='chapter_content')
        content = div_tag.text
        f.write(li_text+':'+content+'\n')
        print(f'{li_text}爬取成功！！')
    f.close()
    print('爬取成功！')
